package com.bieyang.anjia.ui.activity;

import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bieyang.anjia.R;
import com.bieyang.anjia.net.NetManager;
import com.bieyang.anjia.utils.Constants;
import com.bieyang.anjia.utils.SharedPrefsUtil;
import com.bieyang.anjia.utils.Show;
import com.wheel.date.NumericWheelAdapter;
import com.wheel.date.OnWheelChangedListener;
import com.wheel.date.WheelView;

public class AcMyInfo extends BaseActivity {
	Button btnBack, btnExit;
	RelativeLayout rlSetExit, rlmodifyAnjia, rlmodifyPhone, rlmodifyEmail,
			rlModifyPassword, rlAddress, rlTime;

	TextView tvAnjiahao, tvEmail, tvPhone, tvTime, tvSex;
	String str;

	private LayoutInflater inflater;
	private PopupWindow pw;
	View view;
	Context con;
	DatePicker date;
	private Dialog dialog;
	private static int START_YEAR = 1920, END_YEAR = 2014;

	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Constants.LOGOUT_SUCESS:
				// Show.toast(con, R.string.tip_logout_ok);

				if (SharedPrefsUtil.getBooleanValue(con, "subIsLogin", false)) {
					Activity ac = SubMain.getActivity();
					if (null != ac) {
						ac.finish();
					}
					SharedPrefsUtil.putValue(con, "subIsLogin", false);
					SharedPrefsUtil.putValue(App.mContext, "password", "");
				}
				if (App.isLogin) {
					SharedPrefsUtil.putValue(App.mContext, "loginMain", false);
					Activity ac = AcMain.getCurrentActivity();
					if (null != ac) {
						ac.finish();
					}
					App.isLogin = false;
				}
				PubService.isrun = false;
				startActivity(new Intent(con, AcTiYan.class));
				finish();

				break;
			case Constants.LOGOUT_FAIL:
				Show.toast(con, R.string.tip_logout_fail);
				break;
			default:
				break;
			}

		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_info);
		initView();

	}

	private void initView() {
		con = AcMyInfo.this;
		OnClick onClick = new OnClick();
		btnBack = (Button) findViewById(R.id.btnBack);
		btnBack.setOnClickListener(onClick);

		rlmodifyAnjia = (RelativeLayout) findViewById(R.id.rlmodifyAnjia);
		rlmodifyAnjia.setOnClickListener(onClick);
		rlmodifyPhone = (RelativeLayout) findViewById(R.id.rlmodifyPhone);
		// rlmodifyPhone.setOnClickListener(onClick);
		rlmodifyEmail = (RelativeLayout) findViewById(R.id.rlmodifyEmail);
		rlmodifyEmail.setOnClickListener(onClick);
		rlModifyPassword = (RelativeLayout) findViewById(R.id.rlModifyPassword);
		rlModifyPassword.setOnClickListener(onClick);

		rlAddress = (RelativeLayout) findViewById(R.id.rlAddress);
		rlAddress.setOnClickListener(onClick);

		rlTime = (RelativeLayout) findViewById(R.id.rlTime);
		rlTime.setOnClickListener(onClick);

		tvTime = (TextView) findViewById(R.id.tvTime);
		tvSex = (TextView) findViewById(R.id.tvSex);

		tvAnjiahao = (TextView) findViewById(R.id.tvAnjiahao);
		tvPhone = (TextView) findViewById(R.id.tvPhone);
		tvPhone.setText(SharedPrefsUtil.getStringValue(con, "phone", ""));
		tvEmail = (TextView) findViewById(R.id.tvEmail);

		btnExit = (Button) findViewById(R.id.btnExit);
		btnExit.setOnClickListener(onClick);

	}

	class OnClick implements android.view.View.OnClickListener {
		@Override
		public void onClick(View v) {
			Intent intent;
			inflater = LayoutInflater.from(con);
			switch (v.getId()) {
			case R.id.btnBack:
				finish();
				break;
			case R.id.btnExit:
				exit();
				break;

			case R.id.rlmodifyAnjia:
				str = tvAnjiahao.getText().toString();
				intent = new Intent(AcMyInfo.this, AcModify.class);

				intent.putExtra("parent", "modifyAnjia:" + str);
				startActivity(intent);

				break;
			// case R.id.rlmodifyPhone:
			// str = tvPhone.getText().toString();
			// intent = new Intent(AcMyInfo.this, AcModify.class);
			// intent.putExtra("parent", "modifyPhone:" + str);
			// startActivity(intent);
			//
			// break;
			case R.id.rlmodifyEmail:
				str = tvEmail.getText().toString();
				intent = new Intent(AcMyInfo.this, AcModify.class);
				intent.putExtra("parent", "modifyEmail:" + str);
				startActivity(intent);
				// startActivity(new Intent(AcMyInfo.this,AcModify.class));
				break;
			case R.id.rlModifyPassword:
				// popWindow();

				startActivity(new Intent(AcMyInfo.this, AcFindPassword.class));
				finish();
				break;

			case R.id.rlTime:
				showDateTimePicker();
				// chooseTime();
				// startActivity(new Intent(AcMyInfo.this,AcMyAddress.class));
				break;

			default:
				break;
			}

		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			finish();
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

	void chooseTime() {
		final Dialog dialog = new Dialog(con);
		View view = inflater.inflate(R.layout.layout_time, null);
		date = (DatePicker) view.findViewById(R.id.datePicker);

		view.findViewById(R.id.btnSure).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						dialog.dismiss();
						tvTime.setText(date.getYear() + "-"
								+ (date.getMonth() + 1) + "-"
								+ date.getDayOfMonth());
					}
				});
		dialog.setCanceledOnTouchOutside(true);
		dialog.setContentView(view);
		dialog.setTitle(con.getString(R.string.choose_time));
		dialog.show();

	}

	void popWindow() {

		view = inflater.inflate(R.layout.layout_sex, null);
		RadioButton rbMan = (RadioButton) view.findViewById(R.id.rbMan);
		RadioButton rbWoMan = (RadioButton) view.findViewById(R.id.rbWoMan);
		// 根据ID找到RadioGroup实例
		// RadioGroup group = (RadioGroup)view.findViewById(R.id.rgSex);
		// //绑定一个匿名监听器
		// group.setOnCheckedChangeListener(new OnCheckedChangeListener() {
		//
		// @Override
		// public void onCheckedChanged(RadioGroup arg0, int arg1) {
		// //获取变更后的选中项的ID
		// int radioButtonId = arg0.getCheckedRadioButtonId();
		// //根据ID获取RadioButton的实例
		// RadioButton rb = (RadioButton) view.findViewById(radioButtonId);
		// //更新文本内容，以符合选中项
		// tv.setText( rb.getText());
		// }
		// });
		//

		if ("男".equals(tvSex.getText().toString().trim())) {
			rbMan.setChecked(true);
		} else {
			rbWoMan.setChecked(true);
		}
		rbMan.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				pw.dismiss();
				tvSex.setText(R.string.man);
			}
		});
		rbWoMan.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				pw.dismiss();
				tvSex.setText(R.string.lady);
			}
		});

		pw = new PopupWindow(view,
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT, false);
		pw.setFocusable(true);
		pw.setAnimationStyle(R.style.AnimationPreview);
		pw.setBackgroundDrawable(con.getResources().getDrawable(
				R.drawable.popup_bg));
		pw.setOutsideTouchable(true);

		pw.showAtLocation(view, Gravity.CENTER, 0, 0);
	}

	/**
	 * @Description: TODO 弹出日期时间选择器
	 */
	private void showDateTimePicker() {
		Calendar calendar = Calendar.getInstance();
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH);
		int day = calendar.get(Calendar.DATE);
		// int hour = calendar.get(Calendar.HOUR_OF_DAY);
		// int minute = calendar.get(Calendar.MINUTE);

		// 添加大小月月份并将其转换为list,方便之后的判断
		String[] months_big = { "1", "3", "5", "7", "8", "10", "12" };
		String[] months_little = { "4", "6", "9", "11" };

		final List<String> list_big = Arrays.asList(months_big);
		final List<String> list_little = Arrays.asList(months_little);

		dialog = new Dialog(this);
		dialog.setTitle("请选择日期");
		// 找到dialog的布局文件
		LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
		View view = inflater.inflate(R.layout.time_layout, null);

		// 年
		final WheelView wv_year = (WheelView) view.findViewById(R.id.year);
		wv_year.setAdapter(new NumericWheelAdapter(START_YEAR, END_YEAR));// 设置"年"的显示数据
		wv_year.setCyclic(true);// 可循环滚动
		wv_year.setLabel("年");// 添加文字
		wv_year.setCurrentItem(year - START_YEAR);// 初始化时显示的数据

		// 月
		final WheelView wv_month = (WheelView) view.findViewById(R.id.month);
		wv_month.setAdapter(new NumericWheelAdapter(1, 12));
		wv_month.setCyclic(true);
		wv_month.setLabel("月");
		wv_month.setCurrentItem(month);

		// 日
		final WheelView wv_day = (WheelView) view.findViewById(R.id.day);
		wv_day.setCyclic(true);
		// 判断大小月及是否闰年,用来确定"日"的数据
		if (list_big.contains(String.valueOf(month + 1))) {
			wv_day.setAdapter(new NumericWheelAdapter(1, 31));
		} else if (list_little.contains(String.valueOf(month + 1))) {
			wv_day.setAdapter(new NumericWheelAdapter(1, 30));
		} else {
			// 闰年
			if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
				wv_day.setAdapter(new NumericWheelAdapter(1, 29));
			else
				wv_day.setAdapter(new NumericWheelAdapter(1, 28));
		}
		wv_day.setLabel("日");
		wv_day.setCurrentItem(day - 1);

		// 时
		// final WheelView wv_hours = (WheelView) view.findViewById(R.id.hour);
		// wv_hours.setAdapter(new NumericWheelAdapter(0, 23));
		// wv_hours.setCyclic(true);
		// wv_hours.setCurrentItem(hour);
		//
		// // 分
		// final WheelView wv_mins = (WheelView) view.findViewById(R.id.mins);
		// wv_mins.setAdapter(new NumericWheelAdapter(0, 59, "%02d"));
		// wv_mins.setCyclic(true);
		// wv_mins.setCurrentItem(minute);

		// 添加"年"监听
		OnWheelChangedListener wheelListener_year = new OnWheelChangedListener() {
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				int year_num = newValue + START_YEAR;
				// 判断大小月及是否闰年,用来确定"日"的数据
				if (list_big
						.contains(String.valueOf(wv_month.getCurrentItem() + 1))) {
					wv_day.setAdapter(new NumericWheelAdapter(1, 31));
				} else if (list_little.contains(String.valueOf(wv_month
						.getCurrentItem() + 1))) {
					wv_day.setAdapter(new NumericWheelAdapter(1, 30));
				} else {
					if ((year_num % 4 == 0 && year_num % 100 != 0)
							|| year_num % 400 == 0)
						wv_day.setAdapter(new NumericWheelAdapter(1, 29));
					else
						wv_day.setAdapter(new NumericWheelAdapter(1, 28));
				}
			}
		};
		// 添加"月"监听
		OnWheelChangedListener wheelListener_month = new OnWheelChangedListener() {
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				int month_num = newValue + 1;
				// 判断大小月及是否闰年,用来确定"日"的数据
				if (list_big.contains(String.valueOf(month_num))) {
					wv_day.setAdapter(new NumericWheelAdapter(1, 31));
				} else if (list_little.contains(String.valueOf(month_num))) {
					wv_day.setAdapter(new NumericWheelAdapter(1, 30));
				} else {
					if (((wv_year.getCurrentItem() + START_YEAR) % 4 == 0 && (wv_year
							.getCurrentItem() + START_YEAR) % 100 != 0)
							|| (wv_year.getCurrentItem() + START_YEAR) % 400 == 0)
						wv_day.setAdapter(new NumericWheelAdapter(1, 29));
					else
						wv_day.setAdapter(new NumericWheelAdapter(1, 28));
				}
			}
		};
		wv_year.addChangingListener(wheelListener_year);
		wv_month.addChangingListener(wheelListener_month);

		// 根据屏幕密度来指定选择器字体的大小
		int textSize = 25;
		wv_day.TEXT_SIZE = textSize;
		// wv_hours.TEXT_SIZE = textSize;
		// wv_mins.TEXT_SIZE = textSize;
		wv_month.TEXT_SIZE = textSize;
		wv_year.TEXT_SIZE = textSize;

		Button btn_sure = (Button) view.findViewById(R.id.btn_datetime_sure);
		Button btn_cancel = (Button) view
				.findViewById(R.id.btn_datetime_cancel);
		// 确定
		btn_sure.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// 如果是个数,则显示为"02"的样式
				String parten = "00";
				DecimalFormat decimal = new DecimalFormat(parten);
				// 设置日期的显示
				tvTime.setText((wv_year.getCurrentItem() + START_YEAR) + "-"
						+ decimal.format((wv_month.getCurrentItem() + 1)) + "-"
						+ decimal.format((wv_day.getCurrentItem() + 1))
				// + " "
				// + decimal.format(wv_hours.getCurrentItem()) + ":"
				// + decimal.format(wv_mins.getCurrentItem())
				);

				dialog.dismiss();
			}
		});
		// 取消
		btn_cancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				dialog.dismiss();
			}
		});
		// 设置dialog的布局,并显示
		dialog.setContentView(view);
		dialog.show();
	}

	void exit() {
		new NetManager().logout(con, handler);
	}

}